const { MembershipOrder, User } = require('../models');
const { generateUniqueId, getMembershipLevelName } = require('../utils/authUtils');
const { validationResult } = require('express-validator');

// 创建会员订单
const createMembershipOrder = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { membership_level, amount } = req.body;
    const userId = req.user.id;

    // 验证会员等级
    const validLevels = [1, 2, 3]; // 假设1-普通会员，2-高级会员，3-VIP会员
    if (!validLevels.includes(membership_level)) {
      return res.status(400).json({ message: '无效的会员等级' });
    }

    // 创建订单
    const order = await MembershipOrder.create({
      id: generateUniqueId(),
      user_id: userId,
      membership_level,
      amount,
      status: 'pending', // 初始状态为待支付
      created_at: new Date()
    });

    // 这里可以添加支付处理逻辑
    // 例如调用第三方支付API，生成支付链接等

    // 模拟支付成功（实际项目中应该根据支付回调来更新）
    // 为了演示，这里直接将状态设置为已支付
    await order.update({ status: 'paid' });

    // 更新用户会员信息
    const user = await User.findByPk(userId);
    if (user) {
      // 计算会员到期时间（假设按年续费）
      const expiryDate = new Date();
      expiryDate.setFullYear(expiryDate.getFullYear() + 1);
      
      await user.update({
        membership_level,
        membership_expiry: expiryDate
      });
    }

    res.status(201).json({
      message: '会员订单创建成功',
      order: {
        id: order.id,
        membership_level_name: getMembershipLevelName(membership_level),
        amount,
        status: order.status,
        created_at: order.created_at
      }
    });
  } catch (error) {
    console.error('创建会员订单失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取用户的会员订单列表
const getUserMembershipOrders = async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 10 } = req.query;
    
    const offset = (page - 1) * limit;

    const { count, rows: orders } = await MembershipOrder.findAndCountAll({
      where: { user_id: userId },
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    const formattedOrders = orders.map(order => ({
      id: order.id,
      membership_level: order.membership_level,
      membership_level_name: getMembershipLevelName(order.membership_level),
      amount: order.amount,
      status: order.status,
      created_at: order.created_at
    }));

    res.status(200).json({
      orders: formattedOrders,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    console.error('获取会员订单列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取单个会员订单详情
const getMembershipOrderById = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 查询订单
    const order = await MembershipOrder.findOne({
      where: { id, user_id: userId }
    });

    if (!order) {
      return res.status(404).json({ message: '订单不存在或无权限查看' });
    }

    const formattedOrder = {
      id: order.id,
      membership_level: order.membership_level,
      membership_level_name: getMembershipLevelName(order.membership_level),
      amount: order.amount,
      status: order.status,
      created_at: order.created_at,
      updated_at: order.updated_at
    };

    res.status(200).json(formattedOrder);
  } catch (error) {
    console.error('获取会员订单详情失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 管理员获取所有会员订单
const getAllMembershipOrders = async (req, res) => {
  try {
    const { page = 1, limit = 20, userId = '', status = '' } = req.query;
    
    const where = {};
    if (userId) where.user_id = userId;
    if (status) where.status = status;

    const offset = (page - 1) * limit;

    const { count, rows: orders } = await MembershipOrder.findAndCountAll({
      where,
      include: [
        { model: User, attributes: ['id', 'username', 'email'] }
      ],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    const formattedOrders = orders.map(order => ({
      id: order.id,
      user: {
        id: order.User.id,
        username: order.User.username,
        email: order.User.email
      },
      membership_level: order.membership_level,
      membership_level_name: getMembershipLevelName(order.membership_level),
      amount: order.amount,
      status: order.status,
      created_at: order.created_at
    }));

    res.status(200).json({
      orders: formattedOrders,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    console.error('获取所有会员订单失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 管理员更新订单状态
const updateOrderStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    // 验证状态值
    const validStatuses = ['pending', 'paid', 'cancelled', 'refunded'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({ message: '无效的订单状态' });
    }

    // 查询订单
    const order = await MembershipOrder.findByPk(id, {
      include: [User]
    });

    if (!order) {
      return res.status(404).json({ message: '订单不存在' });
    }

    // 更新订单状态
    await order.update({ status });

    // 如果订单状态变为已支付，更新用户会员信息
    if (status === 'paid' && order.status !== 'paid') {
      const user = order.User;
      if (user) {
        // 计算会员到期时间（假设按年续费）
        const expiryDate = new Date();
        expiryDate.setFullYear(expiryDate.getFullYear() + 1);
        
        await user.update({
          membership_level: order.membership_level,
          membership_expiry: expiryDate
        });
      }
    }

    res.status(200).json({ message: '订单状态更新成功', order });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  createMembershipOrder,
  getUserMembershipOrders,
  getMembershipOrderById,
  getAllMembershipOrders,
  updateOrderStatus
};